<template>
  <div class="private-chat-dialog">
    <div class="dialog-overlay" @click="$emit('close')"></div>
    
    <div class="dialog-content">
      <div class="dialog-header">
        <h3>👥 申请私人聊天</h3>
        <button @click="$emit('close')" class="close-btn">×</button>
      </div>
      
      <div class="dialog-body">
        <p class="dialog-description">
          选择你想要私聊的玩家，发送申请后等待对方同意即可开始语音聊天。
        </p>
        
        <!-- 玩家列表 -->
        <div class="players-selection">
          <h4>在线玩家（可多选）</h4>
          

          
          <div class="players-grid">
            <div 
              v-for="player in availablePlayers" 
              :key="player.id"
              class="player-option"
              :class="{ 
                selected: selectedPlayerIds.includes(player.id),
                disabled: !canChatWith(player.id)
              }"
              @click="toggleSelect(player.id)"
            >
              <div class="player-avatar">
                {{ player.name.charAt(0) }}
              </div>
              <div class="player-info">
                <span class="player-name">{{ player.name }}</span>
                <div class="player-status">
                  <span v-if="isInPublicChat(player.id)" class="status-badge public">
                    📢 公聊中
                  </span>
                  <span v-if="getPrivateChatCount(player.id) > 0" class="status-badge private">
                    👥 私聊({{ getPrivateChatCount(player.id) }})
                  </span>
                  <span v-if="isPlayerMuted(player.id)" class="status-badge muted">
                    🔇 已禁音
                  </span>
                  <span v-if="!canChatWith(player.id)" class="status-badge disabled">
                    ❌ 不可用
                  </span>
                </div>
              </div>
              <div class="connection-indicator" :class="getConnectionQuality()">
                📶
              </div>
            </div>
          </div>
        </div>
        
        <!-- 申请详情已移除 -->
        
        <!-- 快速选项已移除 -->
      </div>
      
      <div class="dialog-footer">
        <div class="footer-info">
          <span v-if="selectedPlayerIds.length" class="selection-count">
            已选择 {{ selectedPlayerIds.length }} 个玩家
          </span>
          <span v-else class="no-selection">
            请选择要私聊的玩家
          </span>
        </div>
        
        <div class="footer-actions">
          <button @click="$emit('close')" class="cancel-btn">
            ❌ 取消
          </button>
          <button 
            @click="sendRequest"
            :disabled="selectedPlayerIds.length === 0 || !canSend"
            class="send-btn"
          >
            发送申请（{{ selectedPlayerIds.length }}）
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex';

export default {
  name: 'PrivateChatDialog',
  data() {
    return {
      selectedPlayerIds: []
    };
  },
  computed: {
    ...mapState('voiceChat', ['chatRooms', 'playerPermissions']),
    ...mapState('players', ['players']),
    ...mapState('session', ['playerId', 'isSpectator']),
    ...mapGetters('voiceChat', ['currentUserRole']),
    
    isStoryteller() {
      // 使用session.isSpectator来判断：
      // isSpectator=true 表示说书人（主持人）
      // isSpectator=false 表示玩家
      return this.isSpectator === true;
    },
    
    // 可选择的玩家
    availablePlayers() {
      console.log('🔍 计算可用玩家列表');
      console.log('当前玩家ID:', this.playerId);
      console.log('当前用户角色:', this.currentUserRole);
      console.log('是否为说书人(基于isSpectator):', this.isStoryteller);
      console.log('session.isSpectator:', this.isSpectator);
      
      // 检查基础数据是否存在
      if (!this.players || !Array.isArray(this.players)) {
        console.warn('❌ 玩家数据不存在或不是数组:', this.players);
        return [];
      }
      
      if (!this.chatRooms || !this.chatRooms.public) {
        console.warn('❌ 语音聊天房间数据不存在:', this.chatRooms);
        return [];
      }
      
      console.log('公共聊天参与者:', this.chatRooms.public.participants);
      console.log('所有玩家数据:', this.players.map(p => ({ id: p.id, name: p.name, isStoryteller: p.isStoryteller })));
      
      // 获取在线玩家（参与公共语音聊天的玩家）
      const onlinePlayerIds = this.chatRooms.public.participants || [];
      console.log('在线玩家ID列表:', onlinePlayerIds);
      
      // 如果没有在线玩家，显示所有玩家（除了自己）
      if (onlinePlayerIds.length === 0) {
        console.log('⚠️ 没有在线玩家，显示所有玩家（除了自己）');
        const allPlayers = this.players.filter(player => player.id !== this.playerId);
        console.log('所有可用玩家（无在线限制）:', allPlayers.map(p => ({ id: p.id, name: p.name })));
        return allPlayers;
      }
      
      // 首先从players数组中获取所有在线玩家
      const playersAvailable = this.players.filter(player => {
        // 排除自己
        if (player.id === this.playerId) {
          console.log(`排除自己: ${player.name} (${player.id})`);
          return false;
        }
        
        // 只显示在线玩家（参与公共语音聊天的玩家）
        if (!onlinePlayerIds.includes(player.id)) {
          console.log(`玩家不在线: ${player.name} (${player.id})`);
          return false;
        }
        
        return true;
      });
      
      // 使用服务器角色/显示名补全不在players数组中的在线用户
      const additionalOnlineUsers = [];
      const roles = this.$store.state.voiceChat.roles;
      const dnMap = this.$store.state.voiceChat.displayNames;
      onlinePlayerIds.forEach(id => {
        if (id === this.playerId) return;
        const existsInPlayers = this.players.find(p => p.id === id);
        if (!existsInPlayers) {
          // 说书人优先
          if (roles && roles.get && roles.get(id) === 'storyteller') {
            additionalOnlineUsers.push({
              id,
              name: this.getStorytellerName(),
              isStoryteller: true
            });
          } else {
            const display = dnMap && dnMap.get && dnMap.get(id);
            additionalOnlineUsers.push({
              id,
              name: (display && display.trim()) || '【访客】',
              isStoryteller: false
            });
          }
        }
      });
      const available = [...playersAvailable, ...additionalOnlineUsers];
      
      console.log('添加了额外在线用户:', additionalOnlineUsers.map(u => ({ id: u.id, name: u.name, isStoryteller: u.isStoryteller })));
      console.log('合并后的可用玩家:', available.map(p => ({ id: p.id, name: p.name, isStoryteller: p.isStoryteller || false })));
      
      console.log('最终可用在线玩家:', available.map(p => ({ id: p.id, name: p.name })));
      return available;
    }
  },
  methods: {
    // 取消启发式识别说书人，全部交由服务器角色
    
    // 获取说书人显示名称
    getStorytellerName() {
      const savedName = localStorage.getItem('storyteller_name') || '';
      const savedStarLevel = localStorage.getItem('storyteller_star_level') || 'trainee';
      
      const starLevels = {
        'trainee': '🌟',
        'one_star': '⭐',
        'two_star': '⭐⭐'
      };
      
      const starIcon = starLevels[savedStarLevel] || '🌟';
      
      if (savedName.trim()) {
        return `【${starIcon}】说书人·${savedName.trim()}`;
      } else {
        return `【${starIcon}】说书人`;
      }
    },
    
    // 判断玩家是否为说书人
    isPlayerStoryteller(player) {
      // 1. 如果isStoryteller属性存在且有效，直接使用
      if (typeof player.isStoryteller === 'boolean') {
        return player.isStoryteller;
      }
      
      // 2. 如果isStoryteller未定义，通过ID模式判断
      // 说书人ID通常是简单的数字（sessionId）
      // 普通玩家ID通常是复杂格式：sessionId_browser_timestamp_randomString
      if (player.id && typeof player.id === 'string') {
        // 如果ID只包含数字，很可能是说书人
        if (/^\d+$/.test(player.id)) {
          return true;
        }
        
        // 如果ID包含下划线和复杂格式，很可能是普通玩家
        if (player.id.includes('_browser_')) {
          return false;
        }
      }
      
      // 3. 默认情况下假设不是说书人
      return false;
    },
    
    // 切换选择
    toggleSelect(playerId) {
      if (!this.canChatWith(playerId)) return;
      const idx = this.selectedPlayerIds.indexOf(playerId);
      if (idx >= 0) {
        this.selectedPlayerIds.splice(idx, 1);
      } else {
        this.selectedPlayerIds.push(playerId);
      }
    },
    
    // 检查是否可以和指定玩家聊天
    canChatWith(playerId) {
      // 访客限制：只有说书人与已入座玩家可以发起和参与私聊
      const roles = this.$store.state.voiceChat.roles;
      const isTargetStory = roles && roles.get && roles.get(playerId) === 'storyteller';
      const isTargetSeated = !!this.players.find(p => p.id === playerId);
      const isTargetEligible = isTargetStory || isTargetSeated;
      if (!isTargetEligible) return false;

      const myId = this.playerId;
      const isSelfStory = roles && roles.get && roles.get(myId) === 'storyteller';
      const isSelfSeated = !!this.players.find(p => p.id === myId);
      const isSelfEligible = isSelfStory || isSelfSeated;
      if (!isSelfEligible) return false;

      // 在线（在公聊参与者中）
      const onlinePlayerIds = this.chatRooms.public.participants || [];
      if (!onlinePlayerIds.includes(playerId)) {
        console.log(`玩家不在线，无法聊天: ${playerId}`);
        return false;
      }
      // 未被禁音
      if (this.isPlayerMuted(playerId)) return false;
      // 说书人或玩家都可邀请（当双方在线）
      return true;
    },
    
    // 可否发送（至少有一人可用）
    canSend() {
      return this.selectedPlayerIds.some(id => this.canChatWith(id));
    },

    // 发送多人申请
    sendRequest() {
      const targets = this.selectedPlayerIds.filter(id => this.canChatWith(id));
      if (targets.length === 0) return;
      this.$emit('request', targets);
      this.$emit('close');
    },
    
    // 快速操作
    // 快速选项已移除
    
    // 状态检查
    isPlayerMuted(playerId) {
      return this.playerPermissions[playerId]?.isMuted || false;
    },
    
    isInPublicChat(playerId) {
      return this.chatRooms.public.participants?.includes(playerId) || false;
    },
    
    getPrivateChatCount(playerId) {
      let count = 0;
      this.chatRooms.private.forEach(room => {
        if (room.active && room.participants.includes(playerId)) {
          count++;
        }
      });
      return count;
    },
    
    getConnectionQuality() {
      // 模拟连接质量
      const qualities = ['excellent', 'good', 'poor'];
      return qualities[Math.floor(Math.random() * qualities.length)];
    },
    
    getPlayerName(playerId) {
      // 0) 服务器角色：storyteller 优先（避免用启发式/ID片段）
      const roles = this.$store.state.voiceChat.roles;
      if (roles && roles.get && roles.has(playerId) && roles.get(playerId) === 'storyteller') {
        const savedName = localStorage.getItem('storyteller_name') || '';
        const star = localStorage.getItem('storyteller_star_level') || 'trainee';
        const starIcon = { trainee: '🌟', one_star: '⭐', two_star: '⭐⭐' }[star] || '🌟';
        return savedName.trim() ? `【${starIcon}】说书人·${savedName.trim()}` : `【${starIcon}】说书人`;
      }
      // 1) 已入座玩家名
      const player = this.players.find(p => p.id === playerId);
      if (player && player.name) return player.name;
      // 2) 服务器同步显示名（包含说书人）
      const dnMap = this.$store.state.voiceChat.displayNames;
      if (dnMap && dnMap.get && dnMap.has(playerId)) {
        const dn = dnMap.get(playerId);
        if (dn && dn.trim()) return dn.trim();
      }
      // 3) 服务器同步角色（player/guest 不提供花名，仅作占位）
      // 4) 兜底
      return '【访客】';
    }
  }
};
</script>

<style lang="scss" scoped>
.private-chat-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10001;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.dialog-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(3px);
}

.dialog-content {
  position: relative;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 10px;
  width: 90vw;
  max-width: 500px;
  max-height: 80vh;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 2px 2px 20px 1px #000;
  backdrop-filter: blur(4px);
  
  // 移动端适配
  @media (max-width: 768px) {
    width: 95vw;
    max-height: 85vh;
    border-radius: 8px;
  }
  
  // 平板适配
  @media (min-width: 769px) and (max-width: 1024px) {
    width: 85vw;
    max-width: 450px;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.4);
  border-radius: 10px 10px 0 0;
  
  h3 {
    color: white;
    margin: 0;
    font-size: 14px;
    font-weight: bold;
  }
  
  .close-btn {
    background: none;
    border: none;
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background-color 0.3s;
    
    &:hover {
      background: rgba(255, 255, 255, 0.1);
    }
  }
  
  // 移动端适配
  @media (max-width: 768px) {
    padding: 12px 16px;
    border-radius: 8px 8px 0 0;
    
    h3 {
      font-size: 16px;
    }
    
    .close-btn {
      width: 24px;
      height: 24px;
      font-size: 14px;
    }
  }
}

.dialog-body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
  
  .dialog-description {
    color: rgba(255, 255, 255, 0.8);
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 20px;
  }
  
  h4 {
    color: white;
    margin: 0 0 12px 0;
    font-size: 14px;
    font-weight: 500;
  }
  
  // 移动端适配
  @media (max-width: 768px) {
    padding: 16px;
    max-height: 65vh;
    
    .dialog-description {
      font-size: 13px;
      margin-bottom: 16px;
    }
    
    h4 {
      font-size: 13px;
      margin-bottom: 10px;
    }
    
    // 移动端滚动条
    &::-webkit-scrollbar {
      width: 3px;
    }
    
    &::-webkit-scrollbar-track {
      background: rgba(255, 255, 255, 0.05);
    }
    
    &::-webkit-scrollbar-thumb {
      background: rgba(255, 215, 0, 0.4);
      border-radius: 2px;
    }
  }
}

.players-selection {
  margin-bottom: 20px;
  
  .players-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 8px;
    
    .player-option {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      border-radius: 8px;
      background: rgba(255, 255, 255, 0.05);
      border: 1px solid rgba(255, 255, 255, 0.1);
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover:not(.disabled) {
        background: rgba(255, 255, 255, 0.1);
      }
      
      &.selected {
        border-color: rgba(255, 255, 255, 0.3);
        background: rgba(255, 255, 255, 0.15);
      }
      
      &.disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
      
      .player-avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        background: linear-gradient(135deg, #9C27B0, #7B1FA2);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
        font-size: 14px;
      }
      
      .player-info {
        flex: 1;
        
        .player-name {
          color: white;
          font-weight: 500;
          display: block;
          margin-bottom: 4px;
        }
        
        .player-status {
          display: flex;
          gap: 6px;
          flex-wrap: wrap;
          
          .status-badge {
            font-size: 10px;
            padding: 2px 6px;
            border-radius: 3px;
            
            &.public {
              background: rgba(33, 150, 243, 0.3);
              color: #2196F3;
            }
            
            &.private {
              background: rgba(156, 39, 176, 0.3);
              color: #9C27B0;
            }
            
            &.muted {
              background: rgba(244, 67, 54, 0.3);
              color: #f44336;
            }
            
            &.disabled {
              background: rgba(158, 158, 158, 0.3);
              color: #999;
            }
          }
        }
      }
      
      .connection-indicator {
        font-size: 12px;
        
        &.excellent { color: #4CAF50; }
        &.good { color: #FFC107; }
        &.poor { color: #f44336; }
      }
    }
  }
}

.selected-player-info {
  margin-bottom: 20px;
  padding: 12px;
  background: rgba(255, 215, 0, 0.1);
  border-radius: 6px;
  border: 1px solid rgba(255, 215, 0, 0.3);
  
  .request-summary {
    .summary-item {
      color: white;
      font-size: 13px;
      margin-bottom: 6px;
      
      strong {
        color: #FFD700;
      }
    }
  }
}

.quick-options {
  margin-bottom: 20px;
  
  .quick-buttons {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    
    .quick-btn {
      padding: 6px 12px;
      background: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
      border-radius: 4px;
      color: white;
      cursor: pointer;
      font-size: 12px;
      transition: background-color 0.3s;
      
      &:hover:not(:disabled) {
        background: rgba(255, 255, 255, 0.3);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(0, 0, 0, 0.3);
  
  .footer-info {
    .selection-count {
      color: white;
      font-size: 13px;
      font-weight: 500;
    }
    
    .no-selection {
      color: rgba(255, 255, 255, 0.6);
      font-size: 13px;
    }
  }
  
  .footer-actions {
    display: flex;
    gap: 12px;
    
    .cancel-btn {
      background: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
      border-radius: 6px;
      padding: 8px 16px;
      color: white;
      cursor: pointer;
      transition: background-color 0.3s;
      font-size: 13px;
      
      &:hover {
        background: rgba(255, 255, 255, 0.3);
      }
    }
    
    .send-btn {
      background: rgba(255, 255, 255, 0.2);
      border: 1px solid rgba(255, 255, 255, 0.3);
      border-radius: 6px;
      padding: 8px 16px;
      color: white;
      cursor: pointer;
      transition: background-color 0.3s;
      font-size: 13px;
      font-weight: bold;
      
      &:hover:not(:disabled) {
        background: rgba(255, 255, 255, 0.3);
      }
      
      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }
  }
}

// 自定义滚动条
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.4);
  border-radius: 3px;
  
  &:hover {
    background: rgba(255, 255, 255, 0.6);
  }
}
</style>